package com.example.adminvue.utils;

import com.alibaba.fastjson.JSON;
import com.example.adminvue.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.UUID;

/**
 * jwt工具类
 */
public class JwtUtil {
    //有限期
    public static final long JWT_TTL = 30 * 60 * 1000L; //30分钟

    //密钥
    public static final String JWT_KEY = "sanjiang";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-","");
        return token;
    }

    /**
     * 生成jwt
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject){
        JwtBuilder builder = getJwtBuilder(subject,null,getUUID());  //设置过期时间
        return builder.compact();
    }

    /**
     * 生成jwt
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject,long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,getUUID());  //设置过期时间
        return builder.compact();
    }

    /**
     * 生成jwt
     * @param id
     * @param subject  token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String id,String subject,long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,id);  //设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalkey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis+ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)  //唯一的ID
                .setSubject(subject)  //主题 可以是json数据
                .setIssuer("sj")  //签发者
                .setIssuedAt(now)  //签发时间
                .signWith(signatureAlgorithm,secretKey)  //使用HS256对称加密算法签名，第二个参数为密钥
                .setExpiration(expDate);
    }

    /**
     * 生成加密后的密钥
     * @return
     */
    private static SecretKey generalkey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
        return key;
    }

    /**
     * 解析
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalkey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) throws Exception  {
//        String jwt = createJWT("1234");
//        System.out.println(jwt);
        Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5MzQ0OWJlYjFlOGE0NGMwYmFiOTZjNzRiNWQ5YmUxNCIsInN1YiI6IntcInVzZXJJZFwiOlwiMlwiLFwidXNlck5hbWVcIjpcInJ5XCIsXCJuaWNrTmFtZVwiOlwi6Iul5L6dXCIsXCJlbWFpbFwiOlwicnlAcXEuY29tXCIsXCJwaG9uZW51bWJlclwiOlwiMTU2NjY2NjY2NjZcIixcInNleFwiOlwiMVwifSIsImlzcyI6InNqIiwiaWF0IjoxNjUwNDQ4NjYxLCJleHAiOjE2NTA0NTIyNjF9.qgDQWnNfHLNcO6ffd7d63EMkv6nV1m7MUMK--Q85QCY");
        String subject = claims.getSubject();
        System.out.println(subject);

    }

    public static String makeTokenMap(User user){
        LinkedHashMap<String,String> map = new LinkedHashMap<>();
        map.put("userId",user.getUserId().toString());
        map.put("userName",user.getUserName());
        map.put("nickName",user.getNickName());
        map.put("email",user.getEmail());
        map.put("phonenumber",user.getPhonenumber());
        map.put("sex",user.getSex());
        String json = JSON.toJSONString(map);
        return json;
    }

}